package com.fractalist.base.core.web.interceptor;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.nutz.json.Json;

import com.fractalist.base.core.constants.SystemConstants;
import com.fractalist.base.core.model.JsonSuccessResponse;
import com.fractalist.base.core.utils.CommonMethod;
import com.fractalist.base.core.utils.StringUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * 校验并转换json数据为action中的map
 * @author radio
 *
 */
public class JsonInterceptor implements Interceptor{

	private static final long serialVersionUID = -888330055812563006L;

	public void destroy() {
		
	}

	public void init() {
		
	}

	/**
	 * 接受前台传递来的json数据，对数据的有效性进行验证，然后将son数据转换成map格式的数据传给action
	 */
	public String intercept(ActionInvocation ai) throws Exception {
		//获取上下文
		ActionContext ac = ai.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE);

		
		Map<String, Object> map = ac.getParameters();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		
		String params = request.getParameter(SystemConstants.JSON_PARAM_NAME);
		Map allMap=request.getParameterMap();
		//将参数列表中所有的参数添加到paramMap中
		if(null!=allMap&&allMap.size()>0){
			Set<String> keys = allMap.keySet();
	        for (Iterator it = keys.iterator(); it.hasNext();) {
	            String key = (String) it.next();
//	            String value="";
//	            value=CommonMethod.getParameterByMap(allMap, key);
	            paramMap.put(key, CommonMethod.getParameterByMap(allMap, key));
	        }
		}
		JsonSuccessResponse res = new JsonSuccessResponse();
		if(params == null || params.equals("")){
			//res.setErrorInfo(-2, ErrorConstants.ERROR_MAP.get(-2));
			map.put("paramMap", paramMap);
			return ai.invoke();
		}else{
			paramMap = (Map<String, Object>)Json.fromJson(params);
			
			map.put("paramMap", paramMap);
			return ai.invoke();
//			if(validateKey((String)paramMap.get(SystemConstants.JSON_AUTH_KEY))){
//				map.put("paramMap", paramMap);
//				return ai.invoke();
//			}else{
//				res.setErrorInfo(-1, ErrorConstants.ERROR_MAP.get(-1));
//			}
		}
		/*PrintWriter out = response.getWriter();
		out.print(JsonUtils.buildJsonStr(res));
		out.close();
		return null;*/
	}
	
	/**
	 * 对接受到的json包进行认证
	 * @return
	 */
	private boolean validateKey(String authKey){
		boolean flag = false;
		Date now = new Date();
		String time = String.valueOf(now.getTime());
		StringBuffer sb = new StringBuffer();
		sb.append("#").append("dsgs").append("$").append(time.substring(0, 4));
		String key = StringUtils.md5(sb.toString());
		if(authKey.equals(key)){
			flag = true;
		}
		return flag;
	}

}
